/* 
* 科技有限公司版权所有（）.
* Copyright (c) 2019,   and/or its affiliates. All rights reserved.
* @Date: 2020.09.01 22:47.
* @Author 
* @Description  项目 - 角色管理 - 菜单分配
**/
<template>
  <div>
    <el-tree :data="menuTreeList" show-checkbox default-expand-all node-key="id" ref="tree" highlight-current :props="defaultProps">
    </el-tree>

    <div style="margin-top: 20px" align="center">
      <el-button type="primary" @click="handleSave()">保存</el-button>
      <el-button @click="handleClear()">清空</el-button>
    </div>
  </div>
</template>

<script>
import { listMenuByRole, allocMenu, fetchTreeList } from '@/api/role';

export default {
  name: "allocMenu",
  data() {
    return {
      roleId: null,
      menuTreeList: [],
      defaultProps: {
        label: 'title',
        children: 'children',
      },
    };
  },
  created() {
    this.roleId = this.$route.params.roleId;
    this.treeList();
    this.getRoleMenu(this.roleId);
  },
  methods: {
    /**
    *@Description
    *@Return .
    **/
    treeList() {
      fetchTreeList().then(response => {
        this.menuTreeList = response.result;
      });
    },
    /**
    *@Description
    *@Return .
    **/
    getRoleMenu(roleId) {
      listMenuByRole(roleId).then(response => {
        let menuList = response.result;
        let checkedMenuIds = [];
        if (menuList != null && menuList.length > 0) {
          for (let i = 0; i < menuList.length; i++) {
            let menu = menuList[i];
            if (menu.parentId !== 0) {
              checkedMenuIds.push(menu.id);
            }
          }
        }
        this.$refs.tree.setCheckedKeys(checkedMenuIds);
      });
    },
    /**
    *@Description
    *@Return 保存 - 按钮.
    **/
    handleSave() {
      let checkedNodes = this.$refs.tree.getCheckedNodes();
      let checkedMenuIds = new Set();
      if (checkedNodes != null && checkedNodes.length > 0) {
        for (let i = 0; i < checkedNodes.length; i++) {
          let checkedNode = checkedNodes[i];
          checkedMenuIds.add(checkedNode.id);
          if (checkedNode.parentId !== 0) {
            checkedMenuIds.add(checkedNode.parentId);
          }
        }
      }
      this.$confirm('是否分配菜单？', '提示', {
        type: 'warning',
        cancelButtonText: '取消',
        confirmButtonText: '确定',
      }).then(() => {
        let params = new URLSearchParams();
        params.append("roleId", this.roleId);
        params.append("menuIds", Array.from(checkedMenuIds));
        allocMenu(params).then(response => {
          this.$message.success('分配成功!');
          this.$router.back();
        })
      })
    },
    /**
    *@Description
    *@Return 清空 - 按钮 - 重置checkbox.
    **/
    handleClear() {
      this.$refs.tree.setCheckedKeys([]);
    }
  }
}
</script>

<style scoped>
</style>
